Ext.onReady(function() {

    Ext.QuickTips.init();
    //元数据的store
    var store2 = new Ext.data.Store({
        storeId: 'store2',
        proxy: new Ext.data.HttpProxy({
            url: 'metadata.action?code=repair'
        }),
        reader: new Ext.data.JsonReader({
            fields: [
                {
                    name: 'name'
                }, {
                    name: 'value'
                }
            ]
        })
    });
    store2.load();

    //获取车辆列表
    var carList_store = new Ext.data.Store({
        storeId: 'store3',
        proxy: new Ext.data.HttpProxy({
            url: 'Get_Car_List.action'
        }),
        reader: new Ext.data.JsonReader({
            fields: [
                {
                    name: 'name'
                }, {
                    name: 'value'
                }
            ]
        })
    });

    carList_store.load();

    //获取驾驶员列表
    var driverList_store = new Ext.data.Store({
        storeId: 'store4',
        proxy: new Ext.data.HttpProxy({
            url: 'Get_Data_List.action?method=driver'
        }),
        reader: new Ext.data.JsonReader({
            fields: [
                {
                    name: 'name'
                }, {
                    name: 'value'
                }
            ]
        })
    });

    driverList_store.load();


    var cardOrArea_store = new Ext.data.Store({
        storeId: 'store3',
        proxy: new Ext.data.HttpProxy({
            url: 'Get_AreaOrCard_List.action'
        }),
        reader: new Ext.data.JsonReader({
            fields: [
                {
                    name: 'name'
                }, {
                    name: 'value'
                }
            ]
        })
    });

    cardOrArea_store.load();


    var toolbar = new Ext.Toolbar({
        id: 'toolbar',
        stateful: true,
        items: ['-', {
                id: 'add-p',
                text: '新增',
                handler: function() {
                    win.show();
                }
            }, '-', {
                id: 'edit-btn',
                text: '编辑',
                handler: function() {
                    edit();
                }
            }, '-', {
                id: 'del-btn',
                text: '删除',
                handler: function() {
                    Ext.MessageBox.show({
                        title: '提示框',
                        msg: ' 确定删除该记录吗？注意，数据删除后将无法恢复！ ',
                        buttons: {
                            'yes': '确定',
                            'no': '取消'
                        },
                        fn: showResult,
                        icon: Ext.MessageBox.QUESTION
                    });

                    function showResult(btn) {
                        if (btn == 'yes') {
                            del();
                        }
                    }

                }
            }, '-', {
                text: '导出Excel',
                handler: function() {
                    window.open('ExportXls_Repair.action?start_time=' + Ext.util.Format.date(Ext.ComponentMgr.get("start_time_form").getValue(), 'Ymd') + '&end_time=' + Ext.util.Format.date(Ext.ComponentMgr.get("end_time_form").getValue(), 'Ymd') + '&type=' + Ext.ComponentMgr.get("type_form").getValue() + '&car=' + Ext.ComponentMgr.get("car_form").getValue() + '&area=' + Ext.ComponentMgr.get("area_form").getValue());
                }
            }, '-']
    });


    var form = new Ext.FormPanel({
        labelAlign: 'form',
        frame: true,
        bodyStyle: 'padding:5px 5px 0',
        width: '100%',
        items: [{
                layout: 'column',
                items: [{
                        columnWidth: .3,
                        layout: 'form',
                        items: [{
                                xtype: 'datefield',
                                altFormats: 'Ymd',
                                format: 'Ymd',
                                dateFormat: 'Ymd',
                                fieldLabel: '起始日期',
                                id: 'start_time_form',
                                emptyText: '起始日期',
                                anchor: '95%'
                            }, new Ext.form.ComboBox({
                                fieldLabel: '车牌号码',
                                queryParam: 'name',
                                autoSelect: false,
                                id: 'car_form',
                                displayField: 'name',
                                valueField: 'name',
                                emptyText: '车牌号码',
                                anchor: '95%',
                                typeAhead: true,
                                triggerAction : 'all',
                                        store: carList_store
                            })]
                    }, {
                        columnWidth: .3,
                        layout: 'form',
                        items: [{
                                xtype: 'datefield',
                                altFormats: 'Ymd',
                                format: 'Ymd',
                                dateFormat: 'Ymd',
                                fieldLabel: '截止日期',
                                emptyText: '截止日期',
                                id: 'end_time_form',
                                anchor: '95%'
                            }, new Ext.form.ComboBox({
                                xtype: 'textfield',
                                fieldLabel: '修理厂',
                                emptyText: '修理厂',
                                displayField: 'name',
                                valueField: 'name',
                                store: cardOrArea_store,
                                id: 'area_form',
                                triggerAction: 'all',
                                anchor: '95%'
                            })]
                    }, {
                        columnWidth: .3,
                        layout: 'form',
                        items: [new Ext.form.ComboBox({
                                fieldLabel: '修理方式',
                                emptyText: '修理方式',
                                displayField: 'name',
                                valueField: 'value',
                                store: store2,
                                triggerAction: 'all',
                                id: 'type_form',
                                anchor: '95%'
                            })]
                    }, {
                        columnWidth: .1,
                        layout: 'form',
                        items: [{
                                xtype: "button",
                                id: 'query_tbar',
                                text: "查  询",
                                width: 60,
                                handler: function() {
                                    store.setBaseParam("start_time", Ext.util.Format.date(Ext.ComponentMgr.get("start_time_form").getValue(), 'Ymd'));
                                    store.setBaseParam("end_time", Ext.util.Format.date(Ext.ComponentMgr.get("end_time_form").getValue(), 'Ymd'));
                                    store.setBaseParam("type", Ext.ComponentMgr.get("type_form").getValue());
                                    store.setBaseParam("car", Ext.ComponentMgr.get("car_form").getValue());
                                    store.setBaseParam("area", Ext.ComponentMgr.get("area_form").getValue());
                                    store.load();
                                }
                            }]
                    }]
            }]
    });

    jReader1 = new Ext.data.JsonReader({
        root: 'data',
        totalProperty: 'totalCount',
        fields: [{
                name: 'id'
            }, {
                name: 'car_code'
            }, {
                name: 'type'
            }, {
                name: 'driver'
            }, {
                name: 'repair_date'
            }, {
                name: 'area'
            }, {
                name: 'repair_price'
            }, {
                name: 'mileage'
            }, {
                name: 'approve_date'
            }, {
                name: 'approve_person'
            }, {
                name: 'clean'
            }, {
                name: 'remark'
            }, {
                name: 'repair_content'
            }]
    });

    var store = new Ext.data.Store({
        storeId: 'store1',
        proxy: new Ext.data.HttpProxy({
            url: 'RepairJson.action'
        }),
        reader: jReader1,
        baseParams: {
        }
    });

    var sm = new Ext.grid.CheckboxSelectionModel({
    });

    var cm = new Ext.grid.ColumnModel([sm, {
            header: '编号',
            sortable: true,
            hidden: true,
            dataIndex: 'id'
        }, {
            header: '车牌号码',
            sortable: true,
            width: 73,
            dataIndex: 'car_code'
        }, {
            header: '维修类型',
            sortable: true,
            width: 70,
            dataIndex: 'type',
            renderer: function(v) {
                if (v == '1') {
                    return '自备修理'
                } else if (v == '2') {
                    return '外协修理'
                } else if (v == '3') {
                    return '应急修理'
                }
            }
        }, {
            header: '维修时间',
            sortable: true,
            width: 74,
            dataIndex: 'repair_date'
        }, {
            header: '维修站',
            sortable: true,
            width: 93,
            dataIndex: 'area'
        }, {
            header: '维修金额',
            sortable: true,
            width: 58,
            dataIndex: 'repair_price'
        }, {
            header: '驾驶员',
            sortable: true,
            width: 67,
            dataIndex: 'driver'
        }, {
            header: '里程表清零',
            sortable: true,
            width: 75,
            dataIndex: 'clean',
            renderer: function(v) {
                if (v == 'yes') {
                    return '是'
                } else {
                    return '否'
                }
            }
        }, {
            header: '批准日期',
            sortable: true,
            width: 75,
            dataIndex: 'approve_date'
        }, {
            header: '批准人',
            sortable: true,
            width: 54,
            dataIndex: 'approve_person'
        }, {
            header: '维修前里程',
            sortable: true,
            width: 80,
            dataIndex: 'mileage'
        }, {
            header: '维修内容',
            sortable: true,
            width: 300,
            dataIndex: 'repair_content'
        }, {
            header: '备注',
            sortable: true,
            width: 300,
            dataIndex: 'remark'
        }]);

    var grid = new Ext.grid.GridPanel({
        id: 'repair_grid',
        store: store,
        anchor: '100% -80',
        viewConfig: {
            forceFit: false
        },
        sm: sm,
        cm: cm,
        frame: true,
        columnLines: true,
        autoWidth: true,
        loadMask: true, // 数据加载时的遮罩功能
        stateful: true,
        stateId: 'grid',
        pageSize: 20,
        bbar: new Ext.PagingToolbar({
            store: store,
            emptyMsg: '无数据',
            displayInfo: true
        })
    });
    store.load();

    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [{
                region: 'center',
                tbar: toolbar,
                layout: 'border',
                items: [{
                        region: 'center',
                        // layout : 'accordion',
                        layout: "anchor",
                        frame: true,
                        deferredRender: false,
                        activeTab: 0,
                        items: [form, grid]
                    }]
            }]
    });

    /**
     * 删除驾驶员数据
     */
    function del() {
        var del_data = Ext.ComponentMgr.get("repair_grid")
                .getSelectionModel().getSelections();
        if (del_data.length == 0) {
            Ext.Msg.alert('提示', '请选择需要删除的数据！');
            return;
        } else {
            var id_array = [];
            for (var i = 0; i < del_data.length; i++) {
                id_array[i] = del_data[i].data.id;
            }
            sendRequest(id_array);
        }
    }

    /**
     * 修改驾驶员数据
     */
    function edit() {
        var edit_data = Ext.ComponentMgr.get("repair_grid")
                .getSelectionModel().getSelections();
        if (edit_data.length != 1) {
            Ext.Msg.alert('提示', '对不起，同时只能修改一条数据');
            return;
        } else {
            win.show();
            repair.getForm().loadRecord(edit_data[0]);
        }
    }

    function sendRequest(data) {
        Ext.Ajax.request({
            url: 'DeleteAction.action',
            params: {
                id: data,
                type: 'repair'
            },
            success: function(response, options) {
                Ext.Msg.alert('提示', '删除成功！');
                store.reload();
            },
            failure: function(response, options) {
                Ext.Msg.alert('提示', '删除失败！');
            }
        });
    }



    var method_store = new Ext.data.Store({
        storeId: 'store1',
        proxy: new Ext.data.HttpProxy({
            url: 'metadata.action?code=repair'
        }),
        reader: new Ext.data.JsonReader({
            fields: [
                {
                    name: 'name'
                }, {
                    name: 'value'
                }
            ]
        })
    });

    method_store.load();


    var repair = new Ext.FormPanel({
        labelAlign: 'repair',
        frame: true,
        bodyStyle: 'padding:5px 5px 0',
        width: 600,
        items: [{
                layout: 'column',
                items: [{
                        columnWidth: .5,
                        layout: 'form',
                        items: [{
                                xtype: 'hidden',
                                name: 'id'
                            }, new Ext.form.ComboBox({
                                fieldLabel: '车牌号码',
                                queryParam: 'name',
                                autoSelect: false,
                                name: 'car_code',
                                displayField: 'name',
                                valueField: 'name',
                                emptyText: '车牌号码',
                                anchor: '95%',
                                typeAhead: true,
                                triggerAction : 'all',
                                        store: carList_store
                            }), new Ext.form.ComboBox({
                                fieldLabel: '驾驶员',
                                name: 'driver',
                                displayField: 'name',
                                valueField: 'name',
                                emptyText: '驾驶员',
                                anchor: '95%',
                                typeAhead: true,
                                triggerAction: 'all',
                                queryParam: 'name',
                                minChars: 2,
                                store: driverList_store
                            }), {
                                xtype: 'datefield',
                                fieldLabel: '维修日期',
                                emptyText: '维修日期（必填）',
                                allowBlank: false,
                                name: 'repair_date',
                                altFormats: 'Ymd',
                                format: 'Ymd',
                                dateFormat: 'Ymd',
                                anchor: '95%'
                            }, {
                                xtype: 'textfield',
                                fieldLabel: '修理厂',
                                allowBlank: false,
                                displayField: 'name',
                                emptyText: '修理厂（必填）',
                                anchor: "95%",
                                name: 'area'
                            }, {
                                xtype: 'numberfield',
                                fieldLabel: '维修金额',
                                emptyText: '维修金额（必填）',
                                allowBlank: false,
                                name: 'repair_price',
                                anchor: '95%'
                            }]
                    }, {
                        columnWidth: .5,
                        layout: 'form',
                        items: [{
                                columnWidth: .5,
                                layout: 'form',
                                items: [{
                                        xtype: 'numberfield',
                                        fieldLabel: '维修前里程',
                                        emptyText: '维修前里程（必填）',
                                        allowBlank: false,
                                        name: 'mileage',
                                        anchor: '95%'
                                    }, {
                                        xtype: 'datefield',
                                        fieldLabel: '批准日期',
                                        emptyText: '批准日期',
                                        name: 'approve_date',
                                        altFormats: 'Ymd',
                                        format: 'Ymd',
                                        dateFormat: 'Ymd',
                                        anchor: '95%'
                                    }, {
                                        xtype: 'textfield',
                                        fieldLabel: '维修批准人',
                                        emptyText: '维修批准人',
                                        name: 'approve_person',
                                        anchor: '95%'
                                    }, new Ext.form.ComboBox({
                                        fieldLabel: '维修方式',
                                        hiddenName: 'type',
                                        store: method_store,
                                        displayField: 'name',
                                        valueField: 'value',
                                        typeAhead: true,
                                        triggerAction: 'all',
                                        emptyText: '---请选择---',
                                        anchor: "80%",
                                        name: 'type',
                                        selectOnFocus: true
                                    }), {
                                        xtype: 'radiogroup',
                                        fieldLabel: '里程表清零',
                                        name: 'clean',
                                        anchor: '95%',
                                        items: [{
                                                boxLabel: '是',
                                                name: 'clean',
                                                inputValue: 'yes'
                                            }, {
                                                boxLabel: '否',
                                                name: 'clean',
                                                inputValue: 'no'
                                            }]
                                    }]
                            }]
                    }]
            }, {
                xtype: 'htmleditor',
                id: 'repair_content',
                name: 'repair_content',
                fieldLabel: '维修内容',
                //height : 120,
                anchor: '98%'
            }, {
                xtype: 'textarea',
                id: 'remark',
                name: 'remark',
                fieldLabel: '备注',
                height: 50,
                anchor: '98%'
            }]
    });

    var win = new Ext.Window({
        id: 'win',
        title: "添加车辆维修记录",
        border: false,
        bodyBorder: false,
        // layout:'fit',
        width: 600,
        closeAction: 'hide',
        modal: true,
        tbar: ['-', {
                text: ' 提交并继续',
                handler: function() {
                    onSubmit();
                }
            }, '-', {
                text: ' 提交并返回',
                handler: function() {
                    onSubmit();
                    win.hide();
                }
            }, '-', {
                text: ' 返回',
                handler: function() {
                    win.hide();
                }
            }, '-', {
                text: ' 重填',
                handler: function() {
                    repair.getForm().reset();
                }
            }, '-'],
        items: [repair]
    });

    function onSubmit() {
        // 提交表单
        if (repair.getForm().isValid()) {
            var submitValues = repair.getForm().getValues();
            for (var param in submitValues) {
                if (repair.form.findField(param)
                        && repair.form.findField(param).emptyText == submitValues[param]) {
                    repair.form.findField(param).setValue(' ');
                }
            }
            repair.getForm().submit({
                url: 'RepairAction.action',
                waitMsg: '数据保存中...',
                submitEmptyText: false,
                success: function(c, d) {
                    Ext.MessageBox.alert("操作信息", "成功信息保存！");
                    repair.getForm().reset();
                    store.reload();
                },
                failure: function(c, d) {
                    Ext.MessageBox.show({
                        title: "操作信息",
                        msg: "信息保存出错，请联系管理员！",
                        buttons: Ext.MessageBox.OK,
                        icon: "ext-mb-error"
                    });
                }
            });
        }
    }

});